<template>
  <div ref="pageRef" class="split-screen">
    <div
      v-for="(item, index) in list"
      :key="index"
      class="item"
      :style="{ width: `${item.w}px`, height: `${item.h}px`, left: `${item.left}px`, top: `${item.top}px` }"
    ></div>
  </div>
</template>

<script setup lang="ts">
import { nextTick, PropType, ref, watch } from 'vue';

const props = defineProps({
  num: {
    type: Number,
    default: 1,
  },
  data: {
    type: Object as PropType<any>,
    default: () => {
      return {};
    },
  },
});

const pageRef = ref();

const list = ref<any>([]);
const streamInfo = ref({ width: 0, height: 0 });
const gap = 16;

// 渲染常规数据，平方根结果为整数 - 1 4 9 16
function renderNormalData() {
  const arr: any = [];
  const sqrtNum = Math.sqrt(props.num);
  const perWidth = (streamInfo.value.width - (sqrtNum - 1) * 16) / sqrtNum;
  const perHeight = (streamInfo.value.height - (sqrtNum - 1) * 16) / sqrtNum;

  for (let i = 0; i < props.num; i++) {
    const data = {
      w: perWidth,
      h: perHeight,
      left: (perWidth + gap) * (i % sqrtNum),
      top: (perHeight + gap) * Math.floor(i / sqrtNum),
    };

    arr.push(data);
  }

  list.value = arr;
}

// 渲染特殊数据 - 6
// 第一个占1，2，4，5，其余的不变
function renderSpecialData() {
  const arr: any = [];
  const blackList = [1, 3, 4];
  const sqrtNum = Math.ceil(Math.sqrt(props.num));
  const perWidth = (streamInfo.value.width - (sqrtNum - 1) * 16) / sqrtNum;
  const perHeight = (streamInfo.value.height - (sqrtNum - 1) * 16) / sqrtNum;

  for (let i = 0; i < sqrtNum ** 2; i++) {
    let data: any = {};
    if (i === 1) {
      data = {
        w: perWidth * 2 + gap,
        h: perHeight * 2 + gap,
        left: 0,
        top: 0,
      };
    } else if (blackList.includes(i)) {
      continue;
    } else {
      data = {
        w: perWidth,
        h: perHeight,
        left: (perWidth + gap) * (i % sqrtNum),
        top: (perHeight + gap) * Math.floor(i / sqrtNum),
        active: false,
      };
    }

    arr.push(data);
  }

  list.value = arr;
}

const testSqrtData = (num: number) => {
  const sqrtNum = parseInt(`${Math.sqrt(num)}`, 10);
  const resetNum = sqrtNum ** 2;

  return num === resetNum;
};

watch(
  () => props.num,
  async (num) => {
    await nextTick();

    if (!pageRef.value) return;

    streamInfo.value = pageRef.value.getBoundingClientRect();

    if (testSqrtData(num)) {
      renderNormalData();
      return;
    }

    renderSpecialData();
  },
  { immediate: true },
);
</script>

<style lang="less" scoped>
.split-screen {
  width: 100%;
  height: 100%;
  position: relative;

  .item {
    background: white;
    box-shadow: 3px 22px 50px -2px rgb(121 120 130 / 15%);
    position: absolute;
    left: 0;
    top: 0;
  }
}
</style>
